package com.yb.guigu.pick.security.handler;

import com.yb.guigu.pick.cache.manager.api.GuiguPickStringCacheManager;
import com.yb.guigu.pick.core.bean.GuiguResult;
import com.yb.guigu.pick.core.constant.HttpConstant;
import com.yb.guigu.pick.core.constant.RedisKeyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 21:50
 * FileName: GuiguPickLogoutSuccessHandler
 * Description:
 */
public class GuiguPickLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    GuiguPickStringCacheManager guiguPickStringCacheManager;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String accessToken = request.getHeader(HttpConstant.AUTH_HEADER);
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();

        List<String> keys = Arrays.asList(String.format(RedisKeyConstant.LOGIN_USER_ACCESS_TOKEN_KEY, username), String.format(RedisKeyConstant.LOGIN_USER_DETAIL_KEY, accessToken));

        guiguPickStringCacheManager.multiDelete(keys);

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        response.getWriter().write(GuiguResult.success("退出成功").toJSON());
    }
}
